package com.eascs.bankloan.controller;

import java.text.DecimalFormat;
import java.text.Format;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.bankloan.entity.O2oBankLoanDataEntity;
import com.eascs.bankloan.entity.O2oBankLoanEntity;
import com.eascs.bankloan.entity.O2oFormEntity;
import com.eascs.bankloan.entity.O2oFromOaBankLoanEntity;
import com.eascs.bankloan.entity.O2oToBankLoanEntity;
import com.eascs.bankloan.entity.OaBankLoanEntity;
import com.eascs.bankloan.service.O2oBankLoanService;
import com.eascs.loan.entity.O2oBankLoanData;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.PaginationRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;

@RestController
@RequestMapping("/rbankloan")
public class O2oBankLoanRestController extends BaseRestController {
	private static Logger log = LoggerFactory.getLogger(O2oBankLoanRestController.class);

	@Autowired
	O2oBankLoanService bankLoanService;

	@RequestMapping(value = "/update")
	@Transactional(transactionManager = "o2oTransactionManager")
	public BaseRestResult<String> update(HttpServletRequest request) {
		String[] billCode = request.getParameterValues("ids");
		if (billCode == null || billCode.length == 0) {
			return BaseRestResult.warn("请选中需要放款的单");
		}
		O2oBankLoanEntity loanEntity = null;
		for (int i = 0; i < billCode.length; i++) {
			loanEntity = new O2oBankLoanEntity();
			loanEntity.setBillCode(billCode[i]);
			loanEntity.setLoanFlg(StatusContexts.O2O_YES);
			loanEntity.setLoanTime(new Date());
			loanEntity.setWfStatus(StatusContexts.O2O_FK_END);
			int j = bankLoanService.update(loanEntity);
			if (j > 0) {
				log.debug("贷款单号为：{}  放款成功", billCode[i]);
				O2oBankLoanDataEntity bankLoanDataEntity = bankLoanService.getEntity(billCode[i]);
				O2oBankLoanData bankLoanData = new O2oBankLoanData();
				bankLoanData.setApplyAmount(bankLoanDataEntity.getApplyAmount());
				bankLoanData.setBillCode(bankLoanDataEntity.getBillCode());
				bankLoanData.setDataType("3");
				bankLoanData.setIsDel(StatusContexts.O2O_NO);
				bankLoanData.setLoanAmount(bankLoanDataEntity.getLoanAmount());
				bankLoanData.setLoanBank(bankLoanDataEntity.getLoanBank());
				bankLoanData.setLoanDate(bankLoanDataEntity.getLoanDate());
				bankLoanData.setLoanerCard(bankLoanDataEntity.getLoanerCard());
				bankLoanData.setLoanerName(bankLoanDataEntity.getLoanerName());
				bankLoanData.setLoanRate(bankLoanDataEntity.getLoanRate());
				bankLoanData.setLoanTerm(bankLoanDataEntity.getLoanTerm());
				User user = UserHolder.getUser();
				log.debug("获取登录用户信息：对象-{}，用户名-{}，用户id-{}", user, user.getCname(), user.getNo());
				bankLoanData.setOpratePsn(user.getCname());
				bankLoanData.setOprateTime(new Date());
				bankLoanData.setUpdatePsn(user.getCname());
				bankLoanData.setUpdateTime(new Date());
				int k = bankLoanService.insert(bankLoanData);
				if (k > 0) {
					log.debug("贷款单号为：{}  向放款表中插入放款数据成功", billCode[i]);
				} else {
					log.debug("贷款单号为：{}  向放款表中插入放款数据失败", billCode[i]);
				}
			} else {
				log.debug("贷款单号为：{}  放款失败", billCode[i]);
			}
		}
		return BaseRestResult.info("放款成功").andRefresh();
	}

	@RequestMapping("/o2o")
	public PaginationRestResult o2o() {
		PageResult<Object[]> pageResult = bankLoanService.findByPage();
		String[] titles = { "贷款单号", "放款银行", "借款人姓名", "放款金额", "贷款类型", "经营平台" };
		SelectDataOption[] selectDataOptions = { null, new SelectDataOption("BANKTYPEO2O"), null, null, new SelectDataOption("OTO_LOAN_TYPE"), null };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles);
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(0);
		paginationInfo.setBuildSelectBox(true);
		paginationInfo.setSelectDataOptions(selectDataOptions);
		paginationInfo.setFormats(new Format[] { null, null, null, new DecimalFormat(",##0.00"), null, null });
		paginationInfo.setRendTo("#o2o_result");
		return PaginationRestResult.buildPaginationRestResult(paginationInfo);
	}

	@RequestMapping("/oa")
	public PaginationRestResult oa(O2oFormEntity entity) {
		entity.setPageSize(Integer.MAX_VALUE);
		String oaurl = "/rbankloan/oa?pageIndex=";
		PageResult<Object[]> pageResult = bankLoanService.findByOaPage(entity);
		String[] titles = { "贷款单号", "放款银行", "借款人姓名", "放款金额", "贷款类型", "经营平台", "放款时间" };
		SelectDataOption[] selectDataOptions = { null, new SelectDataOption("BANKTYPEO2O"), null, null, new SelectDataOption("OTO_LOAN_TYPE"), null };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles, oaurl);
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(0);
		paginationInfo.setBuildSelectBox(true);
		paginationInfo.setSelectDataOptions(selectDataOptions);
		paginationInfo.setFormats(new Format[] { null, null, null, new DecimalFormat(",##0.00"), null, null });
		paginationInfo.setRendTo("#oa_result");
		return PaginationRestResult.buildPaginationRestResult(paginationInfo);
	}

	@RequestMapping("/upoa")
	public HtmlRestResult upoa(HttpServletRequest request) {
		String[] billCode = request.getParameterValues("ids");
		if (billCode == null || billCode.length == 0) {
			return new HtmlRestResult("请选中需要放款的单");
		}
		User user = UserHolder.getUser();
		O2oFromOaBankLoanEntity foe = null;
		OaBankLoanEntity obk = null;
		O2oToBankLoanEntity obko2o = null;
		StringBuffer billcodes = new StringBuffer();
		StringBuffer billd = new StringBuffer();
		String billcode_ = "";
		for (int i = 0; i < billCode.length; i++) {
			billcodes.append("'" + billCode[i] + "',");
			billd.append(billCode[i] + ",");
			if (billCode[i].indexOf("O2O") >= 0) {
				obk = bankLoanService.findByOaEntity(billCode[i]);
				foe = new O2oFromOaBankLoanEntity();
				foe.setBillCode(obk.getBillCode());
				foe.setCustermerName(obk.getCustomerName());
				foe.setLoanActualTime(new Date());
				foe.setLoanApplyAmount(obk.getLoanAmount());
				foe.setLoanapplyNo(obk.getLoanapplyNo());
				foe.setLoanBank(obk.getBankType());
				foe.setLoanBankAmount(obk.getLoanAmount());
				foe.setLoanIdNo(obk.getIdcard());
				foe.setLoanPlanTime(new Date());
				foe.setLoanRate(obk.getRate());
				foe.setLoanStatus(StatusContexts.O2O_NO);
				foe.setLoanTerm(obk.getLoanterm());
				foe.setLoanType(obk.getLoanType());
				foe.setLoanUserName(obk.getLoanerName());
				foe.setLtdName(obk.getNamecn());
				foe.setOperatorName(user.getCname());
				foe.setOperatorNo(user.getNo());
				foe.setUpdateTime(new Date());
				int t = bankLoanService.getOaO2oOverdueCount(billCode[i]);
				if (t <= 0) {
					int k = bankLoanService.insert(foe);
					if (k > 0) {
						log.debug("贷款单号为：{}  向放款表中插入放款数据成功", billCode[i]);
					} else {
						log.debug("贷款单号为：{}  向放款表中插入放款数据失败", billCode[i]);
					}
				} else {
					int k = bankLoanService.update(foe);
					if (k > 0) {
						log.debug("贷款单号为：{}  向放款表中更新放款数据成功", billCode[i]);
					} else {
						log.debug("贷款单号为：{}  向放款表中更新放款数据失败", billCode[i]);
					}
				}
			} else {
				obko2o = bankLoanService.findByO2oToEntity(billCode[i]);
				foe = new O2oFromOaBankLoanEntity();
				foe.setBillCode(obko2o.getBillCode());
				foe.setCustermerName(obko2o.getCustomerName());
				foe.setLoanActualTime(new Date());
				foe.setLoanApplyAmount(obko2o.getLoanAmount());
				foe.setLoanapplyNo(obko2o.getLoanapplyNo());
				foe.setLoanBank(obko2o.getBankType());
				foe.setLoanBankAmount(obko2o.getBankloanAmount());
				foe.setLoanIdNo(obko2o.getIdcard());
				foe.setLoanPlanTime(obko2o.getInterestDate());
				foe.setLoanRate(obko2o.getRate());
				foe.setLoanStatus(StatusContexts.O2O_NO);
				foe.setLoanTerm(obko2o.getLoanterm());
				foe.setLoanType(obko2o.getLoanType());
				foe.setLoanUserName(obko2o.getLoanerName());
				foe.setLtdName(obko2o.getNamecn());
				foe.setOperatorName(user.getCname());
				foe.setOperatorNo(user.getNo());
				foe.setUpdateTime(new Date());
				int t = bankLoanService.getOaO2oOverdueCount(billCode[i]);
				if (t <= 0) {
					int k = bankLoanService.insert(foe);
					if (k > 0) {
						log.debug("贷款单号为：{}  向放款表中插入放款数据成功", billCode[i]);
					} else {
						log.debug("贷款单号为：{}  向放款表中插入放款数据失败", billCode[i]);
					}
				} else {
					int k = bankLoanService.update(foe);
					if (k > 0) {
						log.debug("贷款单号为：{}  向放款表中更新放款数据成功", billCode[i]);
					} else {
						log.debug("贷款单号为：{}  向放款表中更新放款数据失败", billCode[i]);
					}
				}
			}

		}
		billcode_ = billcodes.substring(0, billcodes.length() - 1);
		String bil = billd.substring(0, billd.length() - 1);
		PageResult<Object[]> pageResult = bankLoanService.findByOaO2oPage(billcode_);
		String[] titles = { "贷款单号", "放款银行", "借款人姓名", "放款金额", "贷款类型", "经营平台", "放款时间" };
		SelectDataOption[] selectDataOptions = { null, new SelectDataOption("BANKTYPEO2O"), null, null, new SelectDataOption("OTO_LOAN_TYPE"), null, null };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles);
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(0);
		paginationInfo.setSelectDataOptions(selectDataOptions);
		paginationInfo.setFormats(new Format[] { null, null, null, new DecimalFormat(",##0.00"), null, null, null });
		ViewContext.put("paginationInfoss", paginationInfo);
		ViewContext.put("ids", bil);
		ViewContext.put("billLength", billCode.length);
		return HtmlRestResult.popHtmlFragment("bankloan/checkbankloan");
	}

	@RequestMapping("/upoaando2o")
	public BaseRestResult<String> update(String ids) {
		String[] id = ids.split(",");
		for (int i = 0; i < id.length; i++) {
			int j = bankLoanService.updateOaOverdue(id[i]);
			if (j > 0) {
				log.debug("贷款单号为：{}  放款成功", id[i]);
			} else {
				log.debug("贷款单号为：{}  放款失败", id[i]);
			}
		}
		return BaseRestResult.info("放款成功").andRefresh();
	}
	
}
